package cn.tjad.tjad2.module.document.viewholder;

import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.lang.reflect.Field;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.data.event.OnCheckedEvent;
import cn.tjad.tjad2.module.common.viewholder.SimpleBaseViewHolder;

public class PermissionBodySelectViewHolder extends SimpleBaseViewHolder<Serializable> {

    @BindView(R.id.name)
    TextView nameTV;
    @BindView(R.id.rb_check)
    RadioButton checkCB;

    private int position;

    public PermissionBodySelectViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }

    public void setChecked(boolean checked) {
        checkCB.setChecked(checked);
    }

    @OnCheckedChanged(R.id.rb_check)
    public void onCheckedChanged(RadioButton radioButton, boolean isChecked) {
        if (isChecked) {
            OnCheckedEvent event = new OnCheckedEvent();
            event.setCheckedPosition(position);
            event.setChecked(true);
            EventBus.getDefault().post(event);
        }
    }

    @Override
    public void setData(Serializable data, int position) {
        this.position = position;
        if (data instanceof String) {
            nameTV.setText((CharSequence) data);
        } else {
            String name = null;
            try {
                Field field = data.getClass().getField("name");
                field.setAccessible(true);
                name = (String) field.get(data);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            nameTV.setText(name);
        }
    }

}
